package com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.impl;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.neusoft.bizcore.web.utils.JsonUtils;
import com.neusoft.neuiotms.dcvm.bean.AttrBean;
import com.neusoft.neuiotms.dcvm.bean.StandardCiBean;
import com.neusoft.neuiotms.dcvm.bean.StandardCiBean.SchemaDef;
import com.neusoft.neuiotms.dcvm.dto.ConfigDTO;
import com.neusoft.neuiotms.dcvm.service.AssetService;
import com.neusoft.neuiotms.dcvm.service.ConfigService;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.constants.CmdbSynConstants;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.converter.CmdbSynSrcDataConverter;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.converter.CmdbSynSrcDataLastConverter;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.converter.CmdbSynSrcDataToLastConverter;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.dto.CmdbSynSrcDataDTO;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.dto.CmdbSynSrcDataLastDTO;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.model.CmdbSynSrcData;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.model.CmdbSynSrcDataLast;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.CmdbSynService;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.CmdbSynSrcDataLastService;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.CmdbSynSrcDataService;
import com.neusoft.neuiotms.dcvm.task.cmdbSyn.service.ItSynApiService;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@Service
public class CmdbSynServiceImpl implements CmdbSynService {
    @Autowired
    private AssetService cmdbMicroService;
    //    @Autowired
    //    private LocationService locationService;
    @Autowired
    private CmdbSynSrcDataService cmdbSynSrcDataService;
    @Autowired
    private CmdbSynSrcDataLastService cmdbSynSrcDataLastService;
    @Autowired
    private CmdbSynSrcDataToLastConverter cmdbSynSrcDataToLastConverter;
    @Autowired
    private CmdbSynSrcDataConverter cmdbSynSrcDataConverter;
    @Autowired
    private CmdbSynSrcDataLastConverter cmdbSynSrcDataLastConverter;
    @Autowired
    private ConfigService configService;

    /** CMDB机柜实例内存缓存 */
    public static final Map<String, JSONObject> RACK_CI_MEM_CACHE = new ConcurrentHashMap<>();

    @Autowired
    private ItSynApiService itSynService;

    static SimpleDateFormat ymd = new SimpleDateFormat("yyyyMMdd");
    static SimpleDateFormat _ymd = new SimpleDateFormat("yyyy-MM-dd");
    // assetNumber:cmdb机柜编码
    private final Map<String, String> listJG = new HashMap<>();
    private final Map<String, JSONObject> mapSchemadefAttr = new HashMap<>();
    List<JSONObject> listSchemasRel = new ArrayList<>();
    private JSONArray syncedItDeviceDataList = new JSONArray();
    private final JSONArray synfieldData = new JSONArray();

    public static final String JG_SCHEMA = "SM_JIG_600";
    // 1、   设置同步IT设备拉取范围：在【配置中心-3D配置】中 "synItRoomCodes" 设置本期业务涉及的房间
    public static final String SYNITROOMCODES = "synItRoomCodes";
    // 2、   设置CMDB实例入库范围：在【配置中心-3D配置】中 "synItDevRoomCodes" 设置本期需要同步的IT设备房间
    public static final String SYNITDEVROOMCODES = "synItDevRoomCodes";
    public static final String SYNITSCHEMASREL = "synItSchemasRel";
    public static final String ASSET_RACK_CODE = "coding";
    public static final String CATE_IT_CODE = "CT_IT";

    @Value(value = "${readlocal: false}")
    private boolean readlocal;

    @Override
    //@Scheduled(initialDelay = 10000, fixedDelay = 365 * 10 * 24 * 3600000) //
    // 每月1号凌晨1点执行一次
    // @Transactional(rollbackFor = Exception.class)
    public void doCmdbSyn() {
        // 初始化映射数据并调用接口
        this.initAndSynData();
        // 入库本次接口返回数据到实时表
        this.addSynDataToTempDB();
        // 计算U位占用
        this.computeCabinetStats();
        // 处理IT设备类型
        this.handAssetTypeCmdbInstance();
        // 维护同步数据库
        this.handleSynDB();
        // 清空全局对象
        this.clearSynData();

    }

    public void initAndSynData() {
        // IT设备类型映射集合
        this.getSchemasRel();
        // 初始化机柜集合
        this.getMatchJG();
        // 初始化类型模具集合
        this.getMapSchemadefAttr();
        final JSONObject synSrcData = this.syncRequestItDeviceData();
        final JSONArray ja = synSrcData.getJSONArray("itDevices");
        CmdbSynServiceImpl.log.info("1、调用IT资产接口，并解析数据：共获取 " + ja.size() + " 条数据");
        this.syncedItDeviceDataList = ja;
    }

    public void addSynDataToTempDB() {
        CmdbSynServiceImpl.log.info("IT资产同步入库待同步数据开始");

        this.syncedItDeviceDataList.forEach(item -> {
            final CmdbSynSrcData data = new CmdbSynSrcData();

            final JSONObject dataItem = (JSONObject) item;
            final Set<String> itemKeySet = dataItem.keySet();

            for (final String key : itemKeySet) {
                if (!this.existFiled(CmdbSynSrcData.class, key)) {
                    continue;
                }
                final String synData = dataItem.getString(key);
                final String name = key.equals("id") ? "deviceId" : key;
                if (key.equals("spec")) {
                    final JSONObject spec = dataItem.getJSONObject(key);
                    if (null != spec) {
                        final String specData =
                                spec.getString("deviceCategory") + "-" + spec.getString("deviceType") + "-"
                                        + spec.getString("producer") + "-" + spec.getString("model");
                        data.setAssetType(specData);
                    }
                }
                try {
                    Field field = null;
                    field = CmdbSynSrcData.class.getDeclaredField(name);
                    final String methodStr = "set" + name.toUpperCase().substring(0, 1) + name.substring(1);
                    Method method = null;
                    // CmdbSynServiceImpl.log.info("addSynDataToTempDB###{}", methodStr);
                    method = CmdbSynSrcData.class.getMethod(methodStr, new Class[] {field.getType() });

                    method.invoke(data, synData);
                } catch (final Exception e) {
                    if (!(e instanceof NoSuchFieldException)) {
                        CmdbSynServiceImpl.log.error("", e);
                    } else {
                        CmdbSynServiceImpl.log.warn(e.getMessage());
                    }
                }

            }

            this.cmdbSynSrcDataService.saveAndFlush(data);

        });
        // //临时测试
        // final List<CmdbSynSrcDataLast> searchAll =
        // this.cmdbSynSrcDataLastService.searchAll();
        // for (final CmdbSynSrcDataLast cmdbSynSrcDataLast : searchAll) {
        // final CmdbSynSrcData data = new CmdbSynSrcData();
        // BeanUtils.copyProperties(cmdbSynSrcDataLast, data);
        // final CmdbSynSrcData result = this.cmdbSynSrcDataService.saveAndFlush(data);
        // CmdbSynServiceImpl.log.info("保存CmdbSynSrcData成功id{}", result.getId());
        // }
        CmdbSynServiceImpl.log.info("IT资产同步入库待同步数据结束");
    }

    private boolean existFiled(Class<?> clazz, String filedName) {
        final Field[] fileds = clazz.getDeclaredFields();
        return Stream.of(fileds).filter(it -> it.getName().equalsIgnoreCase(filedName)).count() > 0;
    }

    public void handAssetTypeCmdbInstance() {
        CmdbSynServiceImpl.log.info("IT资产设备同步cmdb开始");

        // 2、  设置CMDB实例入库范围：在【配置中心-3D配置】中 "synItDevRoomCodes" 设置本期需要同步的IT设备房间
        final String synItDevRoomCodes = this.configService.details(CmdbSynServiceImpl.SYNITDEVROOMCODES).getData();
        final List<String> roomIdList = Arrays.asList(synItDevRoomCodes.split(","));

        // 二期入库的IT设备（非技术原因）
        final List<CmdbSynSrcData> iiRangeList = this.cmdbSynSrcDataService
                .findAll().stream().filter(it -> roomIdList.contains(it.getRoomId()))
                .collect(Collectors.toList());

        //      final List<CmdbSynSrcData> iiRangeList = this.cmdbSynSrcDataService
        //                .findAll().stream().filter(it -> (this.listSchemasRel.stream()
        //                        .filter(s -> s.getString("src").equals(it.getAssetType())).count() == 0)
        //                        && roomIdList.contains(it.getRoomId()))
        //                .collect(Collectors.toList());

        CmdbSynServiceImpl.log.info("本次同步CMDB的IT设备数量为：{}", iiRangeList.size());

        final List<JSONObject> defaultAssetType = new ArrayList<>();
        iiRangeList.stream().map(it -> it.getAssetType()).distinct().forEach(assetType -> {
            if (this.listSchemasRel.stream().filter(s -> s.getString("src").equals(assetType)).count() == 0) {
                final JSONObject jo = new JSONObject();
                jo.put("src", assetType);
                jo.put("target", "SM_IT_DEFAULT");
                defaultAssetType.add(jo);
            }
        });
        this.listSchemasRel.addAll(defaultAssetType);

        CmdbSynServiceImpl.log.info("合并后的模型映射配置数量：{}", this.listJG.size());

        // 打印日志
        final Map<String, Long> counting = iiRangeList.stream()
                .collect(Collectors.groupingBy(CmdbSynSrcData::getAssetType, Collectors.counting()));
        CmdbSynServiceImpl.log.info("设备类型分布：{}", JSON.toJSONString(counting));

        //        counting.entrySet().stream().forEach(entry -> {
        //            CmdbSynServiceImpl.log.info("本次同步CMDB的IT设备类型：{}, 数量：{}", entry.getKey(), entry.getValue());
        //        });

        int searchAddCount = 0;
        int searchUpdateCount = 0;
        int searchDelCount = 0;
        for (final JSONObject x : this.listSchemasRel) {
            final String srcName = x.getString("src");
            final String assetType = x.getString("target");

            // 确定本次新增的设备
            List<CmdbSynSrcData> searchAdd = this.cmdbSynSrcDataService.searchAdd(srcName);

            searchAdd =
                    searchAdd.stream().filter(it -> roomIdList.contains(it.getRoomId())).collect(Collectors.toList());

            final List<CmdbSynSrcDataDTO> searchAddDTO = searchAdd == null ? new ArrayList<>()
                    : this.cmdbSynSrcDataConverter.toListDTO(searchAdd);
            this.handAddCmdb(searchAddDTO, assetType);
            searchAddCount += searchAddDTO.size();

            // 确定本次更新的设备
            List<CmdbSynSrcData> searchUpdate = this.cmdbSynSrcDataService.searchUpdate(srcName);
            searchUpdate = searchUpdate.stream().filter(it -> roomIdList.contains(it.getRoomId()))
                    .collect(Collectors.toList());
            final List<CmdbSynSrcDataDTO> searchUpdateDTO = searchUpdate == null ? new ArrayList<>()
                    : this.cmdbSynSrcDataConverter.toListDTO(searchUpdate);
            this.handUpdateCmdb(searchUpdateDTO, assetType);
            searchUpdateCount += searchUpdateDTO.size();

            // 确定本次删除的设备
            final List<CmdbSynSrcDataLast> searchDel = this.cmdbSynSrcDataLastService.searchDel(srcName);
            final List<CmdbSynSrcDataLastDTO> searchDelDTO = searchDel == null ? new ArrayList<>()
                    : this.cmdbSynSrcDataLastConverter.toListDTO(searchDel);
            this.handDelCmdb(searchDelDTO, assetType);
            searchDelCount += searchDelDTO.size();

            final List<CmdbSynSrcDataDTO> insertOrUpdateData = new ArrayList<>();
            insertOrUpdateData.addAll(searchAddDTO);
            insertOrUpdateData.addAll(searchUpdateDTO);
            this.cmdbSynSrcDataService.updateStatus(insertOrUpdateData);
        }
        CmdbSynServiceImpl.log.info("本次新增的设备数量：{}, 更新的设备数量：{}，删除的设备数量：{}", searchAddCount, searchUpdateCount,
                searchDelCount);
        CmdbSynServiceImpl.log.info("IT资产设备同步cmdb结束");
    }

    public void handleSynDB() {
        CmdbSynServiceImpl.log.info("IT资产同步维护数据库开始");
        this.handOtherTypeData();
        this.cmdbSynSrcDataLastService.deleteAllInBatch();
        this.cmdbSynSrcDataLastService
                .saveAll(this.cmdbSynSrcDataToLastConverter.toListDTO(this.cmdbSynSrcDataService.findAll()));
        this.cmdbSynSrcDataService.deleteAllInBatch();
        CmdbSynServiceImpl.log.info("IT资产同步维护数据库结束");

    }

    public void handOtherTypeData() {
        final List<String> listAssetType = this.listSchemasRel.stream().map(x -> x.getString("src"))
                .collect(Collectors.toList());
        final List<CmdbSynSrcData> notInRelData = this.cmdbSynSrcDataService.findByAssetTypeNotIn(listAssetType);
        if (null != notInRelData) {
            notInRelData.forEach(x -> {
                x.setSynCmdb("0");
                x.setSynRemark("设备类型无法匹配平台类型");
            });
        }
        this.cmdbSynSrcDataService.saveAll(notInRelData);
    }

    public void clearSynData() {
        this.listSchemasRel.clear();
        this.listJG.clear();
        this.mapSchemadefAttr.clear();
        this.syncedItDeviceDataList.clear();
        this.synfieldData.clear();

    }

    public void handAddCmdb(final List<CmdbSynSrcDataDTO> searchAdd, final String assetType) {
        int addNum = 0;
        int errorNum = 0;
        CmdbSynServiceImpl.log.info("IT资产同步新增设备类型{}开始", assetType);
        for (final CmdbSynSrcDataDTO cmdbSynSrcData : searchAdd) {
            final Map<String, Object> instanceMap = new HashMap<>();
            try {
                String rackCode = "";
                final String rack = cmdbSynSrcData.getRack();
                if (!rack.isEmpty()) {
                    rackCode =
                            JsonUtils.jsonToPojo(rack, JSONObject.class).getString(CmdbSynServiceImpl.ASSET_RACK_CODE);
                }
                // check设备所在机柜是否在目标机柜集合内
                if (!this.listJG.keySet().contains(rackCode)) {
                    CmdbSynServiceImpl.log.error("IT资产同步设备类型{},设备{}无法与cmdb机柜匹配", assetType, cmdbSynSrcData.getName());
                    cmdbSynSrcData.setSynCmdb("0");
                    cmdbSynSrcData.setSynRemark("IT资产同步设备所在机柜不在同步范围内");
                    continue;
                }
                instanceMap.put("name", cmdbSynSrcData.getName());
                instanceMap.put("code", cmdbSynSrcData.getCoding());
                instanceMap.put("schemadef", assetType);

                final Map<String, String> attrs = this.getCmdbAttrs(cmdbSynSrcData, assetType, rackCode);
                instanceMap.putAll(attrs);
                if (attrs.isEmpty()) {
                    CmdbSynServiceImpl.log.error("IT资产同步设备类型{}设备名称{}属性异常", assetType, cmdbSynSrcData.getName());
                    cmdbSynSrcData.setSynCmdb("0");
                    cmdbSynSrcData.setSynRemark("IT资产同步设备属性异常");
                    errorNum++;
                    continue;
                }
                CmdbSynServiceImpl.log.info("开始创建实例{}", JsonUtils.pojoToJson(instanceMap));
                JSONObject result = null;
                result = this.cmdbMicroService.createInstances(JsonUtils.pojoToJson(instanceMap));
                String instanceId = null;
                final JSONObject data = result.getJSONObject("data");
                if (null != data) {
                    instanceId = data.getString("_id");
                    cmdbSynSrcData.setSynCmdb("1");
                    cmdbSynSrcData.setCmdbCode(data.getString("code"));
                    addNum++;
                }
                CmdbSynServiceImpl.log.info("结束创建实例{}", instanceId);
                try {
                    Thread.sleep(500);
                } catch (final InterruptedException e) {
                    CmdbSynServiceImpl.log.error("", e);
                }
            } catch (final Exception e) {
                CmdbSynServiceImpl.log.error("", e);
                CmdbSynServiceImpl.log.info("创建实例失败", JsonUtils.pojoToJson(instanceMap));
                cmdbSynSrcData.setSynCmdb("1");
                cmdbSynSrcData.setSynRemark("创建实例失败");
                errorNum++;
            }
        }
        CmdbSynServiceImpl.log.info("IT资产同步新增设备类型{}结束，共新增设备数量{},新增失败数量{}", assetType, addNum, errorNum);
    }

    public void handUpdateCmdb(final List<CmdbSynSrcDataDTO> searchUpdate, final String assetType) {
        int updateNum = 0;
        int errorNum = 0;
        CmdbSynServiceImpl.log.info("IT资产同步更新设备类型{}开始", assetType);

        for (final CmdbSynSrcDataDTO cmdbSynSrcData : searchUpdate) {
            final JSONObject cmdbRackCiJsonObj = CmdbSynServiceImpl.RACK_CI_MEM_CACHE.get(cmdbSynSrcData.getCoding());
            final String instanceId = null != cmdbRackCiJsonObj ? cmdbRackCiJsonObj.getString("code") : null;
            if (null == instanceId) {
                continue;
            }
            final List<AttrBean> listAttr = new ArrayList<>();
            try {
                String rackCode = "";
                final String rack = cmdbSynSrcData.getRack();
                if (!rack.isEmpty()) {
                    rackCode =
                            JsonUtils.jsonToPojo(rack, JSONObject.class).getString(CmdbSynServiceImpl.ASSET_RACK_CODE);
                }
                // check设备所在机柜是否在目标机柜集合内
                if (!this.listJG.keySet().contains(rackCode)) {
                    CmdbSynServiceImpl.log.error("IT资产同步设备类型{},设备{}无法与cmdb机柜匹配", cmdbSynSrcData.getName(), assetType);
                    cmdbSynSrcData.setSynCmdb("0");
                    cmdbSynSrcData.setSynRemark("IT资产同步设备所在机柜不在同步范围内");
                    errorNum++;
                    continue;
                }

                //                instanceId = this.cmdbSynSrcDataLastService.searchByCoding(cmdbSynSrcData.getCoding()).getCmdbCode();

                final Map<String, String> attrs = this.getCmdbAttrs(cmdbSynSrcData, assetType, rackCode);
                if (attrs.isEmpty()) {
                    CmdbSynServiceImpl.log.error("IT资产同步设备类型{}设备名称{}属性异常", assetType, cmdbSynSrcData.getName());
                    cmdbSynSrcData.setSynCmdb("0");
                    cmdbSynSrcData.setSynRemark("IT资产同步设备属性异常");
                    continue;
                }

                final Iterator<Entry<String, String>> it = attrs.entrySet().iterator();
                while (it.hasNext()) {
                    final AttrBean item = new AttrBean();
                    final Entry<String, String> next = it.next();
                    item.setKey(next.getKey());
                    item.setValue(next.getValue());
                    listAttr.add(item);
                }
                CmdbSynServiceImpl.log.info("开始更新实例: {}, attr: {}", instanceId, JsonUtils.pojoToJson(listAttr));

                final JSONObject updateInstanceResult =
                        this.cmdbMicroService.updateInstancesAttrs(instanceId, listAttr);
                final String data = updateInstanceResult.getString("data");
                if (null != data) {
                    cmdbSynSrcData.setSynCmdb("1");
                    cmdbSynSrcData.setCmdbCode(instanceId);
                    updateNum++;
                }
                CmdbSynServiceImpl.log.info("结束更新实例{}", instanceId);
                try {
                    Thread.sleep(500);
                } catch (final InterruptedException e) {
                    CmdbSynServiceImpl.log.error("", e);

                }
            } catch (final Exception e) {
                CmdbSynServiceImpl.log.info("更新实例{},属性{}失败", instanceId, JsonUtils.pojoToJson(listAttr));
                CmdbSynServiceImpl.log.error("", e);
                cmdbSynSrcData.setSynCmdb("1");
                cmdbSynSrcData.setCmdbCode(instanceId);
                cmdbSynSrcData.setSynRemark("更新cmdb失败" + e.getMessage());
                errorNum++;
            }
        }
        CmdbSynServiceImpl.log.info("IT资产同步更新设备类型{}结束，共更新设备数量{},更新失败数量{}", assetType, updateNum, errorNum);
    }

    public void handDelCmdb(final List<CmdbSynSrcDataLastDTO> searchDel, final String assetType) {
        final int delNum = 0;
        int errorNum = 0;
        CmdbSynServiceImpl.log.info("IT资产同步删除设备类型{}开始", assetType);

        for (final CmdbSynSrcDataLastDTO cmdbSynSrcData : searchDel) {
            final String instanceId = cmdbSynSrcData.getCmdbCode();
            try {

                if (StringUtils.isNotBlank(instanceId)) {
                }
            } catch (final Exception e1) {
                CmdbSynServiceImpl.log.error("", e1);
                CmdbSynServiceImpl.log.info("删除实例{}失败", instanceId);
                errorNum++;
            }
        }
        CmdbSynServiceImpl.log.info("IT资产同步删除设备类型{}结束，共更新设备数量{},更新失败数量{}", assetType, delNum, errorNum);
    }

    //    public void handDelCmdb(final List<CmdbSynSrcDataLastDTO> searchDel, final String assetType) {
    //        int delNum = 0;
    //        int errorNum = 0;
    //        CmdbSynServiceImpl.log.info("IT资产同步删除设备类型{}开始", assetType);
    //
    //        for (final CmdbSynSrcDataLastDTO cmdbSynSrcData : searchDel) {
    //            String instanceId = null;
    //            final List<AttrBean> listAttr = new ArrayList<>();
    //            try {
    //                String rackCode = "";
    //                final String rack = cmdbSynSrcData.getRack();
    //                if (!rack.isEmpty()) {
    //                    rackCode =
    //                            JsonUtils.jsonToPojo(rack, JSONObject.class).getString(CmdbSynServiceImpl.ASSET_RACK_CODE);
    //                }
    //                // check设备所在机柜是否在目标机柜集合内
    //                if (!this.listJG.keySet().contains(rackCode)) {
    //                    CmdbSynServiceImpl.log.error("IT资产同步设备类型{},设备{}无法与cmdb机柜匹配", cmdbSynSrcData.getName(), assetType);
    //                    continue;
    //                }
    //
    //                final Map<String, Object> instanceMap = new HashMap<>();
    //                instanceId = this.cmdbSynSrcDataLastService.searchByCoding(cmdbSynSrcData.getCoding()).getCmdbCode();
    //                final Map<String, String> attrs = this.getCmdbBasicDelAttr();
    //                final Iterator<Entry<String, String>> it = attrs.entrySet().iterator();
    //                while (it.hasNext()) {
    //                    final AttrBean item = new AttrBean();
    //                    final Entry<String, String> next = it.next();
    //                    item.setKey(next.getKey());
    //                    item.setValue(next.getValue());
    //                    listAttr.add(item);
    //                }
    //                instanceMap.put("attrs", listAttr);
    //                CmdbSynServiceImpl.log.info("开始更新删除标识实例{}", JsonUtils.pojoToJson(instanceMap));
    //                this.cmdbMicroService.updateInstancesAttrs(instanceId, listAttr);
    //                delNum++;
    //                CmdbSynServiceImpl.log.info("结束更新删除标识实例{}", instanceId);
    //                Thread.sleep(500);
    //
    //            } catch (final Exception e1) {
    //                CmdbSynServiceImpl.log.error("", e1);
    //                CmdbSynServiceImpl.log.info("更新实例{},属性{}失败", instanceId, JsonUtils.pojoToJson(listAttr));
    //                cmdbSynSrcData.setSynCmdb("1");
    //                cmdbSynSrcData.setCmdbCode(instanceId);
    //                cmdbSynSrcData.setSynRemark("更新cmdb失败" + e1.getMessage());
    //                errorNum++;
    //            }
    //        }
    //        CmdbSynServiceImpl.log.info("IT资产同步删除设备类型{}结束，共更新设备数量{},更新失败数量{}", assetType, delNum, errorNum);
    //    }

    public Map<String, String> getBasicAttr() {
        final Map<String, String> basicAttrs = new HashMap<>();
        basicAttrs.put(CmdbSynConstants.SYN_FLAG_ATTR_CODE, "1");
        basicAttrs.put(CmdbSynConstants.ASSET_DEL_ATTR_CODE, "0");
        basicAttrs.put(CmdbSynConstants.SYN_TIME_ATTR_CODE, String.valueOf(new Date().getTime()));
        return basicAttrs;
    }

    public JSONObject syncRequestItDeviceData() {
        //        final JSONObject jo = JSON.parseObject(objects[0].toString());
        // String json="{\"iTDevices\":[{\"id\":72198,\"dataCenterId\":758528777,\"dataCenterName\":\"中国移动（云南昆明）枢纽数据中心\",\"buildingName\":\"枢纽生产楼\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"rackName\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-E13\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC01-WAF01-WAG5010\",\"coding\":\"YNKM-PS-IDC01-WAF01-WAG5010\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":false,\"monitoring\":false,\"netTier\":null,\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"安全设备\",\"deviceType\":\"WAF\",\"producer\":\"启明星辰\",\"model\":\"WAG5010\",\"sn\":null,\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":null,\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":2,\"slots\":null,\"spec\":null},\"rack\":{\"id\":61665,\"rackType\":\"自有业务\",\"name\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-E13\",\"coding\":\"RACK-871-01-01-301-E13\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"五千瓦功率机柜\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"totalUnit\":42,\"testTotalUnit\":0,\"entire\":false,\"col\":5,\"colEn\":null,\"ordinal\":13,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":null,\"depth\":null,\"width\":null,\"height\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":5000.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":5000.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-01-01-301-E00\",\"ups\":\"Kin1四楼电力机房24#UPS系统1#UPS输出柜D10K4250AKin2四楼电力机房24#UPS系统2#UPS输出柜D11K4250A\",\"intId\":null},\"startUnit\":18,\"endUnit\":19,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":null,\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"安全设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":null,\"specJson\":null,\"units\":2,\"weight\":null,\"powerType\":null,\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null},{\"id\":72199,\"dataCenterId\":758528777,\"dataCenterName\":\"中国移动（云南昆明）枢纽数据中心\",\"buildingName\":\"枢纽生产楼\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"rackName\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"coding\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":false,\"monitoring\":false,\"netTier\":null,\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"安全设备\",\"deviceType\":\"WAF\",\"producer\":\"启明星辰\",\"model\":\"WAG5010\",\"sn\":null,\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":null,\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":2,\"slots\":null,\"spec\":null},\"rack\":{\"id\":61818,\"rackType\":\"自有业务\",\"name\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"coding\":\"RACK-871-01-01-301-Q10\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"五千瓦功率机柜\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"totalUnit\":42,\"testTotalUnit\":0,\"entire\":false,\"col\":17,\"colEn\":null,\"ordinal\":10,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":null,\"depth\":null,\"width\":null,\"height\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":5000.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":5000.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-01-01-301-Q00\",\"ups\":\"Kin1四楼电力机房26#UPS系统1#UPS输出柜H08K1250AKin2四楼电力机房26#UPS系统2#UPS输出柜H09K1250A\",\"intId\":null},\"startUnit\":18,\"endUnit\":19,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":null,\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"安全设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":null,\"specJson\":null,\"units\":2,\"weight\":null,\"powerType\":null,\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null}],\"responseCode\":\"0\",\"responseDesc\": \"成功\"}";
        //	String json = "{\"iTDevices\":[{\"id\":72199,\"dataCenterId\":758528777,\"dataCenterName\":\"中国移动（云南昆明）枢纽数据中心\",\"buildingName\":\"枢纽生产楼\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"rackName\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"tenantId\":null,\"tenantName\":null,\"sellerName\":null,\"company\":null,\"tenantType\":null,\"indentId\":null,\"indentName\":null,\"submitDept\":null,\"name\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"coding\":\"YNKM-PS-IDC01-WAF02-WAG5010\",\"assetTag\":null,\"intId\":null,\"mountDate\":null,\"maintenanceDate\":null,\"networking\":false,\"monitoring\":false,\"netTier\":null,\"evaluation\":false,\"status\":\"在服\",\"contactNameNum\":null,\"spec\":{\"deviceCategory\":\"安全设备\",\"deviceType\":\"WAF\",\"producer\":\"启明星辰\",\"model\":\"WAG5010\",\"sn\":null,\"size\":{\"depth\":null,\"width\":null,\"height\":null},\"weight\":null,\"power\":{\"powerType\":null,\"voltage\":null,\"rated\":null,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"units\":2,\"slots\":null,\"spec\":null},\"rack\":{\"id\":61818,\"rackType\":\"自有业务\",\"name\":\"五华区昆明枢纽楼三楼IDC机房/SBJJ01-IDC-Q10\",\"coding\":\"RACK-871-01-01-301-Q10\",\"leaseStatus\":\"占用\",\"status\":\"在服\",\"spec\":\"五千瓦功率机柜\",\"roomName\":\"五华区昆明枢纽楼三楼IDC机房\",\"roomId\":61605,\"totalUnit\":42,\"testTotalUnit\":0,\"entire\":false,\"col\":17,\"colEn\":null,\"ordinal\":10,\"locationLabel\":null,\"plannedUse\":null,\"setupTime\":null,\"retireNetTime\":null,\"useCorp\":null,\"relatedSupplyCompany\":null,\"integrateAir\":null,\"powerSupplyType\":null,\"coldPartCode\":null,\"coldChildPartCode\":null,\"rackStatus\":null,\"shortName\":null,\"assetCoding\":null,\"occupy\":null,\"occupyUposNum\":null,\"idleUposNum\":null,\"size\":null,\"depth\":null,\"width\":null,\"height\":null,\"power\":{\"powerType\":\"AC\",\"voltage\":null,\"rated\":5000.0000,\"totalPowerRated\":null,\"totalActualPower\":null,\"actual\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"assetCode\":null},\"rated\":5000.0000,\"powerType\":\"AC\",\"powerConsumeType\":null,\"pdf\":\"RACK-871-01-01-301-Q00\",\"ups\":\"Kin1四楼电力机房26#UPS系统1#UPS输出柜H08K1250AKin2四楼电力机房26#UPS系统2#UPS输出柜H09K1250A\",\"intId\":null},\"startUnit\":18,\"endUnit\":19,\"mountOperatedTime\":null,\"portTotal\":null,\"idlePortTotal\":null,\"remark\":null,\"asset\":null,\"snmp\":{\"hostid\":null,\"proxyid\":null,\"templateid\":[],\"ip\":null,\"port\":161,\"ver\":\"V2C\",\"community\":null,\"internetIp\":null},\"ipAddresses\":null,\"outlets\":null,\"projectName\":null,\"businessOwner\":null,\"ipv4Manage\":null,\"ipv6Manage\":null,\"setupTime\":null,\"rackSurface\":null,\"lifecycleStatus\":null,\"businessDesc\":null,\"deviceCategory\":\"安全设备\",\"depth\":null,\"width\":null,\"height\":null,\"deviceType\":null,\"slots\":null,\"sn\":null,\"specJson\":null,\"units\":2,\"weight\":null,\"powerType\":null,\"rated\":null,\"voltage\":null,\"powerConsumeType\":null,\"powerAccessMethod\":null,\"propertyType\":null,\"direction\":null,\"powerConsume\":null,\"calorificValue\":null,\"serverRam\":null,\"cpu\":null,\"disk\":null,\"actual\":null,\"powerOnDto\":null,\"useRate\":null}],\"responseCode\": \"0\",\"responseDesc\": \"成功\"}";

        JSONObject jo = null;
        if (this.readlocal) {
            jo = this.itSynService.getMockItDevicesData();
        } else {
            jo = this.itSynService.getItDevicesData();
        }

        return jo;
    }

    /**
     * @param searchData
     * @return
     */
    public Map<String, String> getCmdbAttrs(final CmdbSynSrcDataDTO searchData, final String assetType,
            final String rackCode) {
        final Map<String, String> attrs = new HashMap<>();

        try {
            attrs.put("cabinet", this.listJG.get(rackCode));
            attrs.put("ubit", searchData.getStartUnit());
            attrs.put("uHeight", searchData.getUnits());
            final JSONObject schemadefAttr = this.mapSchemadefAttr.get(assetType);
            //            attrs.put("ratedPower",
            //                    schemadefAttr.getString("ratedPower").isEmpty() ? "0" : schemadefAttr.getString("ratedPower"));

            final JSONObject specJsonObj = JSON.parseObject(searchData.getSpec());

            double ratedPower = 0;
            if (specJsonObj.containsKey("power")
                    && (null != specJsonObj.getJSONObject("power"))
                    && specJsonObj.getJSONObject("power").containsKey("rated")) {

                ratedPower = specJsonObj.getJSONObject("power").getDoubleValue("rated");
            }
            attrs.put("ratedPower", String.valueOf(ratedPower));

            double weight = 0;
            if (specJsonObj.containsKey("weight")) {

                weight = specJsonObj.getDoubleValue("weight");
            }
            attrs.put("weight", String.valueOf(weight));

            //            attrs.put("weight", schemadefAttr.getString("weight").isEmpty() ? "0" : schemadefAttr.getString("weight"));
            attrs.put("model", schemadefAttr.getString("model"));
            attrs.putAll(this.getBasicAttr());
        } catch (final NumberFormatException e) {
            CmdbSynServiceImpl.log.error("设置设备{}属性异常{}", searchData.getName(), e.getMessage());
            CmdbSynServiceImpl.log.error("", e);
        }
        return attrs;

    }

    public Map<String, String> getCmdbBasicDelAttr() {
        final Map<String, String> basicAttrs = new HashMap<>();
        basicAttrs.put(CmdbSynConstants.ASSET_DEL_ATTR_CODE, "1");
        basicAttrs.put(CmdbSynConstants.SYN_FLAG_ATTR_CODE, "1");
        basicAttrs.put(CmdbSynConstants.SYN_TIME_ATTR_CODE, String.valueOf(new Date().getTime()));
        return basicAttrs;
    }

    private void getMatchJG() {

        // 获取定制机房下柜列集合
        //        final ConfigDTO details = this.configService.details(CmdbSynServiceImpl.SYNITROOMCODES);
        //        final String roomData = details.getData();
        //        final String[] roomCodeAray = roomData.split(",");
        //        for (final String roomCode : roomCodeAray) {
        //            final List<LocationCiBean> deepLocationsByOne = this.locationService.getDeepLocationsByOne(roomCode, 1);
        //            deepLocationsByOne.forEach(item -> {
        //                final List<StandardCiBean> allCiByForeignInst =
        //                        this.cmdbMicroService.getAllCiByCatetoriesAndForeign("CT_RACK", "location",
        //                                item.getCode());
        //                allCiByForeignInst.forEach(x -> {
        //                    final AttrBean assetNumberAttr =
        //                            x.getAttrs().stream().filter(it -> "assetNumber".equals(it.getKey()))
        //                                    .findFirst().orElse(null);
        //                    if (null != assetNumberAttr) {
        //                        this.listJG.add(String.valueOf(assetNumberAttr.getValue()));
        //                    }
        //
        //                });
        //            });
        //        }

        final List<StandardCiBean> allJiguiInstList = this.cmdbMicroService.getAllCiBySchema("SM_JIG_600");
        allJiguiInstList.forEach(x -> {
            final AttrBean assetNumberAttr =
                    x.getAttrs().stream().filter(it -> "assetNumber".equals(it.getKey()))
                            .findFirst().orElse(null);
            if (null != assetNumberAttr) {
                this.listJG.put(String.valueOf(assetNumberAttr.getValue()), x.getCode());
            }

        });

        CmdbSynServiceImpl.log.info("CMDB预置机柜个数为：{} ", this.listJG.size());
        if (CmdbSynServiceImpl.log.isDebugEnabled()) {
            CmdbSynServiceImpl.log.debug("只更新机柜 {} 下的IT资产", String.join(",", this.listJG.keySet()));
        }
    }

    private void getSchemasRel() {
        // 获取定制模型映射关系
        final ConfigDTO details = this.configService.details(CmdbSynServiceImpl.SYNITSCHEMASREL);
        final String schemasRelStr = details.getData();
        this.listSchemasRel = JSON.parseArray(schemasRelStr).toJavaList(JSONObject.class);

        if (CmdbSynServiceImpl.log.isDebugEnabled()) {
            CmdbSynServiceImpl.log.debug("模型映射关系配置: {}", JsonUtils.pojoToJson(this.listSchemasRel));
        }
    }

    private void getMapSchemadefAttr() {
        // 查找分类“CT_IT”下的所有模型（交换机、服务器、存储设备等）
        final List<SchemaDef> allSchemasByCatetories =
                this.cmdbMicroService.getAllSchemasByCatetories(CmdbSynServiceImpl.CATE_IT_CODE);
        allSchemasByCatetories.forEach(item -> {
            final JSONObject attr = new JSONObject();
            item.getAttrs().forEach(x -> {
                if (x.getField().equals("model")) {
                    attr.put("model", String.valueOf(x.getDvalue()));
                } else if (x.getField().equals("ratedPower")) {
                    attr.put("ratedPower", String.valueOf(x.getDvalue()));
                } else if (x.getField().equals("weight")) {
                    attr.put("weight", String.valueOf(x.getDvalue()));
                }
            });
            this.mapSchemadefAttr.put(item.getCode(), attr);
        });

        if (CmdbSynServiceImpl.log.isDebugEnabled()) {
            CmdbSynServiceImpl.log.debug("IT分类模型属性: {}", JsonUtils.pojoToJson(this.mapSchemadefAttr));
        }

    }

    /**
     * 计算U位占用、功率、称重等统计，更新cmdb
     */
    private void computeCabinetStats() {
        final Map<String, List<JSONObject>> rackMap = new ConcurrentHashMap<>();

        // 本次同步的所有设备
        this.syncedItDeviceDataList.stream().forEach(it -> {
            final JSONObject item = (JSONObject) it;
            final JSONObject rackObj = (JSONObject) item.get("rack");
            final String rackCoding = (String) rackObj.get("coding");
            if (rackMap.containsKey(rackCoding)) {
                rackMap.get(rackCoding).add(item);
            } else {
                final List<JSONObject> list = new ArrayList<>();
                list.add(item);
                rackMap.put(rackCoding, list);
            }
        });

        for (final Map.Entry<String, List<JSONObject>> entry : rackMap.entrySet()) {
            final String rackCoding = entry.getKey();

            CmdbSynServiceImpl.log.info("处理机柜：{}", rackCoding);

            final List<JSONObject> itdevices = entry.getValue();
            JSONObject cmdbRackCiJsonObj = CmdbSynServiceImpl.RACK_CI_MEM_CACHE.get(rackCoding);
            if (null == cmdbRackCiJsonObj) {
                final JSONObject result = this.cmdbMicroService.filter("assetNumber", rackCoding);
                if (CmdbSynServiceImpl.log.isDebugEnabled()) {
                    CmdbSynServiceImpl.log.debug("机柜：{}", result.toString());
                }
                if ((null != result) && !result.getJSONArray("data").isEmpty()) {
                    cmdbRackCiJsonObj = result.getJSONArray("data").getJSONObject(0);
                    CmdbSynServiceImpl.RACK_CI_MEM_CACHE.put(rackCoding, cmdbRackCiJsonObj);
                }
            }

            if (null == cmdbRackCiJsonObj) {
                CmdbSynServiceImpl.log.warn("未找到机柜：{}", rackCoding);
                continue;
            }

            if (CmdbSynServiceImpl.log.isDebugEnabled()) {
                CmdbSynServiceImpl.log.debug("{}:{}", rackCoding, cmdbRackCiJsonObj.toJSONString());
            }

            final String cmdbCode = cmdbRackCiJsonObj.getString("code");

            final Map<String, String> attrs = new HashMap<>();
            final int totalUnit = itdevices.get(0).getJSONObject("rack").getIntValue("totalUnit");
            /********* U位统计 *********/
            attrs.put("uHeight", String.valueOf(totalUnit));

            String uInfo = this.initUInfoField(totalUnit);
            uInfo = this.setUInfoField(uInfo, itdevices);
            attrs.put("uInfo", uInfo);
            final long usedU = uInfo.chars().filter(it -> it == '1').count();
            attrs.put("usedU", String.valueOf(usedU));
            attrs.put("uCapacity", String.valueOf((usedU * 1.0) / totalUnit));

            /********* 功率统计 *********/
            final Double realPower = itdevices.stream().map(it -> {
                if (it.containsKey("spec") && (null != it.getJSONObject("spec"))
                        && it.getJSONObject("spec").containsKey("power")
                        && (null != it.getJSONObject("spec").getJSONObject("power"))
                        && it.getJSONObject("spec").getJSONObject("power").containsKey("rated")) {

                    return it.getJSONObject("spec").getJSONObject("power").getDoubleValue("rated");
                }
                return 0.0;
            }).reduce(0.0, (a, b) -> a + b);

            final Object ratedPowerAttrJsonObj = cmdbRackCiJsonObj
                    .getJSONArray("attrs").stream()
                    .filter(it -> "ratedPower".equalsIgnoreCase(((JSONObject) it).getString("key")))
                    .findFirst().orElse(null);

            // CMDB预置额定功率
            double ratedPower = 1;
            if (null != ratedPowerAttrJsonObj) {
                ratedPower = Double.valueOf(((JSONObject) ratedPowerAttrJsonObj).getString("value"));
            }

            attrs.put("realPower", String.valueOf(realPower));
            attrs.put("eCapacity", String.valueOf((realPower * 1.0) / ratedPower));

            /********* 承重统计 *********/
            final Double realWeight = itdevices.stream().map(it -> {
                if (it.containsKey("spec") && (null != it.getJSONObject("spec"))
                        && it.getJSONObject("spec").containsKey("weight")) {

                    return it.getJSONObject("spec").getDoubleValue("weight");
                }
                return 0.0;
            }).reduce(0.0, (a, b) -> a + b);

            // 默认设置为1000
            final double maxWeight = 1000;

            attrs.put("realWeight", String.valueOf(realWeight));
            attrs.put("wCapacity", String.valueOf((realWeight * 1.0) / maxWeight));

            attrs.put(CmdbSynConstants.ASSET_DEL_ATTR_CODE, "0");
            attrs.put(CmdbSynConstants.SYN_TIME_ATTR_CODE, String.valueOf(new Date().getTime()));

            final List<AttrBean> listAttr = new ArrayList<>();
            final Iterator<Entry<String, String>> it = attrs.entrySet().iterator();
            while (it.hasNext()) {
                final AttrBean item = new AttrBean();
                final Entry<String, String> next = it.next();
                item.setKey(next.getKey());
                item.setValue(next.getValue());
                listAttr.add(item);
            }

            CmdbSynServiceImpl.log.info("开始更新机柜{},属性信息:{}", cmdbCode,
                    JsonUtils.pojoToJson(listAttr));
            this.cmdbMicroService.updateInstancesAttrs(cmdbCode, listAttr);
            CmdbSynServiceImpl.log.info("结束更新机柜{}", cmdbCode);

        }

    }

    private String initUInfoField(int totalUnit) {
        final StringBuilder sb = new StringBuilder();
        for (int i = 0; i < totalUnit; i++) {
            sb.append("0");
        }
        return sb.toString();
    }

    /**
     * 根据startUnit和endUnit更新uInfo状态
     *
     * @param totalUnit
     * @return
     */
    private String setUInfoField(String initStr, List<JSONObject> itdevices) {
        if (null != itdevices) {
            final char[] arr = initStr.toCharArray();

            for (int i = 0; i < itdevices.size(); i++) {
                final JSONObject jo = itdevices.get(i);
                int startUnit = jo.getIntValue("startUnit");
                int endUnit = jo.getIntValue("endUnit");

                if (startUnit > endUnit) {
                    startUnit = startUnit + endUnit;
                    endUnit = startUnit - endUnit;
                    startUnit = startUnit - endUnit;
                }

                for (int j = startUnit - 1; j < endUnit; j++) {
                    if ((j < arr.length) && (j > -1)) {
                        arr[j] = '1';
                    }
                }
            }
            initStr = String.valueOf(arr);
        }
        return initStr;
    }

}
